<?PHP
/*
  Plugin for download from youtube (http://youtube.com/)
  Developed by seth <xd dot seth at gmail dot com - http://elrincondeseth.wordpress.com>
*/

$plugins[] = array('youtube','@http://www.youtube.com/watch\?v=(.+)@');

function youtube_download($url, $extra)
{
    $file = downloadUrl($url);
    if(($file['code']<200) or ($file['code']>299)) {
        return array(
                        'status'       => STATUS_ERROR,
                        'status_error' => 'Download error. Response code #'.$file['code'],
                    );
    }else{
        if(isset($extra['HD']) and ($extra['HD'] == TRUE)){
            preg_match('@\'IS_HD_AVAILABLE\': (.+?),@',$file['content'],$matchs);
            
            if ($matchs[1] == 'true'){
                preg_match('@"fmt_url_map": "22\|(.+?),@', $file['content'], $matchs);
                    
                $file = downloadUrlRecursive($matchs[1]);
                if(($file['code']<200) or ($file['code']>299)) {
                    return array(
                                    'status'       => STATUS_ERROR,
                                    'status_error' => 'Download error. Response code #'.$file['code'],
                                );
                }else{
                    return array(
                                    'status'  => STATUS_DOWNLOADED,
                                    'content' => $file['content']
                                );
                }
                
            }else{
                return array(
                                'status'       => STATUS_ERROR,
                                'status_error' => 'HD not available',
                            );
            }

        }else{
            preg_match('@"t": "(.+?)", @',$file['content'],$matchs);
            parse_str(parse_url($url,PHP_URL_QUERY),$query);
            $url = 'http://www.youtube.com/get_video?video_id='.$query['v'].'&t='.$matchs[1];
            
            $file = downloadUrlRecursive($url);
            if(($file['code']<200) or ($file['code']>299)) {
                return array(
                                'status'       => STATUS_ERROR,
                                'status_error' => 'Download error. Response code #'.$file['code'],
                            );
            }else{
                return array(
                                'status'  => STATUS_DOWNLOADED,
                                'content' => $file['content']
                            );
            }
        }
    }
}


function youtube_getName($url)
{
    $html = downloadUrl($url);
    if(($html['code']<200) or ($html['code']>299)) {
        parse_str(parse_url($url,PHP_URL_QUERY),$query);
        return $query['v'].'.flv';
    }else{
        preg_match('@<meta name="title" content="(.+?)">@',$html['content'],$matchs);
        return $matchs[1].'.flv';    
    }
}
?>